package cn.sykj.car.controller;

import cn.sykj.car.common.ResponseBean;
import cn.sykj.car.common.StatusCode;
import cn.sykj.car.entity.Users;
import cn.sykj.car.exception.LoginException;
import cn.sykj.car.jwt.JWTUtil;
import cn.sykj.car.service.IDictionaryService;
import cn.sykj.car.service.IUsersService;
import io.swagger.annotations.Api;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@Api(hidden = false, tags = {"登录 前端控制器"})
public class LoginController extends BaseController{
    @Resource
    private IUsersService usersService;
    @Resource
    private IDictionaryService dictionaryService;
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseBean login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              HttpServletRequest request) {
        Users userBean = usersService.getUserByName(username);
        if (userBean == null) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND,null);
        }
        if (userBean.getPasswd().equals(password)) {
            if(userBean.getDelFlag().equals(0)){
                this.writeLog("用户登陆", userBean.getId(), userBean.getUserName());
                return new ResponseBean(HttpStatus.OK, HttpStatus.OK.value(), "登录成功", JWTUtil.sign(username, password));
            }else{
                return new ResponseBean(StatusCode.USER_DELETE,null);
            }

        } else {
            throw new LoginException();
        }
    }

    @RequestMapping(value = "/checkLogin",method = RequestMethod.POST)
    @RequiresAuthentication
//    @RequiresAuthentication
//    @RequiresRoles("ADMIN")
//    @RequiresPermissions("admin:*")
    public ResponseBean checkLogin() {
        return new ResponseBean(StatusCode.OK, null);
    }

    @RequestMapping(value = "/401")
    public ResponseBean exception401() {
        throw new AuthenticationException();
//        return new ResponseBean(HttpStatus.UNAUTHORIZED, 401, "Unauthorized", "");
    }
}